document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const cultureSelect = document.getElementById('culture');
    const quantitySlider = document.getElementById('quantity');
    const quantityDisplay = document.getElementById('quantity-display');
    const generateBtn = document.getElementById('generate-btn');
    const generateInternetBtn = document.getElementById('generate-internet-btn');
    const resetBtn = document.getElementById('reset-btn');
    const exportBtn = document.getElementById('export-btn');
    const resultsContainer = document.getElementById('results-container');
    const generatedCount = document.getElementById('generated-count');
    const resultCount = document.getElementById('result-count');
    const genderGroup = document.getElementById('gender-group');
    const typeOptions = document.querySelectorAll('.type-option');
    const showMeaningCheckbox = document.getElementById('show-meaning');

    // 更新数量显示
    quantitySlider.addEventListener('input', () => {
        quantityDisplay.textContent = quantitySlider.value;
    });

    // 切换生成类型
    typeOptions.forEach(option => {
        option.addEventListener('click', function () {
            typeOptions.forEach(opt => opt.classList.remove('active'));
            this.classList.add('active');

            if (this.dataset.type === 'internet') {
                cultureSelect.value = 'internet';
                genderGroup.style.display = 'none';
                generateInternetBtn.style.display = 'flex';
                generateBtn.style.display = 'none';
            } else {
                cultureSelect.value = 'random';
                genderGroup.style.display = 'block';
                generateInternetBtn.style.display = 'none';
                generateBtn.style.display = 'flex';
            }
        });
    });

    // 生成姓名函数
    function generateNames() {
        const culture = cultureSelect.value;
        const quantity = parseInt(quantitySlider.value);
        const genderRadios = document.getElementsByName('gender');
        let selectedGender = 'any';

        for (const radio of genderRadios) {
            if (radio.checked) {
                selectedGender = radio.value;
                break;
            }
        }

        const allowUnisex = document.getElementById('allow-unisex').checked;
        const showMeaning = showMeaningCheckbox.checked;

        // 清空结果容器
        resultsContainer.innerHTML = '';

        // 如果选择随机文化，随机选择一种文化
        const selectedCulture = culture === 'random' ?
            getRandomCulture() : culture;

        // 检查所选文化是否有数据
        if (!nameDatabase[selectedCulture]) {
            resultsContainer.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>所选文化暂无数据，请尝试其他文化</p>
                </div>
            `;
            return;
        }

        // 生成姓名
        const names = [];

        for (let i = 0; i < quantity; i++) {
            let genderPool;

            // 根据选择的性别确定生成池
            if (selectedGender === 'any') {
                genderPool = ['male', 'female'];
                if (allowUnisex) genderPool.push('unisex');
            } else {
                genderPool = [selectedGender];
                if (allowUnisex && Math.random() > 0.7) {
                    genderPool.push('unisex');
                }
            }

            // 随机选择性别
            const gender = genderPool[Math.floor(Math.random() * genderPool.length)];

            // 获取对应文化的姓名列表
            const cultureNames = nameDatabase[selectedCulture];

            if (cultureNames && cultureNames[gender] && cultureNames[gender].length > 0) {
                const nameList = cultureNames[gender];
                const randomName = nameList[Math.floor(Math.random() * nameList.length)];

                names.push({
                    name: randomName.name,
                    meaning: randomName.meaning,
                    origin: selectedCulture,
                    gender: gender,
                    type: 'real'
                });
            } else {
                // 如果所选性别没有数据，尝试其他性别
                let fallbackGender = gender === 'male' ? 'female' : 'male';
                if (cultureNames[fallbackGender] && cultureNames[fallbackGender].length > 0) {
                    const nameList = cultureNames[fallbackGender];
                    const randomName = nameList[Math.floor(Math.random() * nameList.length)];

                    names.push({
                        name: randomName.name,
                        meaning: randomName.meaning,
                        origin: selectedCulture,
                        gender: fallbackGender,
                        type: 'real'
                    });
                } else if (cultureNames.unisex && cultureNames.unisex.length > 0) {
                    const nameList = cultureNames.unisex;
                    const randomName = nameList[Math.floor(Math.random() * nameList.length)];

                    names.push({
                        name: randomName.name,
                        meaning: randomName.meaning,
                        origin: selectedCulture,
                        gender: 'unisex',
                        type: 'real'
                    });
                } else {
                    // 如果所有性别都没有数据
                    resultsContainer.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-exclamation-circle"></i>
                            <p>所选文化暂无数据，请尝试其他文化</p>
                        </div>
                    `;
                    return;
                }
            }
        }

        // 显示姓名
        displayNames(names, showMeaning);
    }

    // 生成网名函数
    function generateInternetNames() {
        const quantity = parseInt(quantitySlider.value);
        const showMeaning = showMeaningCheckbox.checked;

        // 清空结果容器
        resultsContainer.innerHTML = '';

        // 生成网名
        const names = [];
        const nameList = nameDatabase.internet.unisex;

        for (let i = 0; i < quantity; i++) {
            // 避免重复选择同一个名字
            let randomIndex;
            let randomName;
            do {
                randomIndex = Math.floor(Math.random() * nameList.length);
                randomName = nameList[randomIndex];
            } while (names.some(n => n.name === randomName.name) && names.length < nameList.length);

            names.push({
                name: randomName.name,
                meaning: randomName.meaning,
                origin: 'internet',
                gender: 'unisex',
                type: 'internet'
            });
        }

        // 显示网名
        displayNames(names, showMeaning);
    }

    // 显示姓名函数
    function displayNames(names, showMeaning) {
        // 获取详情面板元素
        const detailsContent = document.querySelector('.details-content');

        // 清空容器
        resultsContainer.innerHTML = '';

        names.forEach(name => {
            const nameCard = document.createElement('div');
            nameCard.className = `name-card ${name.type === 'internet' ? 'internet' : ''}`;
            nameCard.innerHTML = `
                <div class="name">${name.name}</div>
                <div class="origin">${getCultureName(name.origin)}</div>
                <div class="gender ${name.gender} ${name.type === 'internet' ? 'internet-tag' : ''}">${name.gender === 'male' ? '男' :
                    name.gender === 'female' ? '女' : '网名'
                }</div>
                <button class="favorite-btn"><i class="far fa-heart"></i></button>
                ${showMeaning ? `<div class="meaning">${name.meaning}</div>` : ''}
            `;

            // 添加点击事件以显示详情
            nameCard.addEventListener('click', function () {
                detailsContent.innerHTML = `
                    <div class="name-detail-header">
                        <div class="detail-name">${name.name}</div>
                    </div>
                    <div class="detail-metadata">
                        <span><i class="fas fa-globe"></i> ${getCultureName(name.origin)}</span>
                        <span><i class="fas fa-${name.gender === 'male' ? 'mars' : name.gender === 'female' ? 'venus' : 'user'}"></i> ${name.gender === 'male' ? '男性' : name.gender === 'female' ? '女性' : '中性'}</span>
                    </div>
                    <div class="detail-meaning">
                        <strong>含义：</strong>${name.meaning || '暂无含义信息'}
                    </div>
                `;
            });

            resultsContainer.appendChild(nameCard);
        });

        // 更新计数
        generatedCount.textContent = names.length;
        resultCount.textContent = `(${names.length})`;

        // 添加收藏功能
        document.querySelectorAll('.favorite-btn').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.stopPropagation();
                const icon = this.querySelector('i');
                this.classList.toggle('active');

                if (this.classList.contains('active')) {
                    icon.classList.remove('far');
                    icon.classList.add('fas');
                } else {
                    icon.classList.remove('fas');
                    icon.classList.add('far');
                }
            });
        });
    }

    // 重置表单
    function resetForm() {
        cultureSelect.value = 'random';
        document.getElementsByName('gender')[0].checked = true;
        quantitySlider.value = 10;
        quantityDisplay.textContent = '10';
        document.getElementById('allow-unisex').checked = true;
        document.getElementById('show-meaning').checked = false;
        resultsContainer.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-file-signature"></i>
                <p>点击"生成姓名"按钮开始创建</p>
            </div>
        `;
        generatedCount.textContent = '0';
        resultCount.textContent = '(0)';

        // 重置类型选择
        typeOptions.forEach(opt => opt.classList.remove('active'));
        document.querySelector('.type-option[data-type="real"]').classList.add('active');
        genderGroup.style.display = 'block';
        generateInternetBtn.style.display = 'none';
        generateBtn.style.display = 'flex';

        // 重置详情面板
        document.querySelector('.details-content').innerHTML = `
            <div class="empty-details">
                <i class="fas fa-hand-pointer"></i>
                <p>点击任意名字查看详细信息</p>
            </div>
        `;
    }

    // 导出结果
    function exportResults() {
        const names = Array.from(document.querySelectorAll('.name'));
        if (names.length === 0) {
            alert('没有可导出的姓名');
            return;
        }

        let content = "生成的姓名列表：\n\n";

        names.forEach(nameEl => {
            const name = nameEl.textContent;
            const origin = nameEl.nextElementSibling.textContent;
            const gender = nameEl.nextElementSibling.nextElementSibling.textContent;

            content += `${name} | ${origin} | ${gender}\n`;
        });

        const blob = new Blob([content], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = '姓名列表.txt';
        document.body.appendChild(a);
        a.click();

        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 0);
    }

    // 特色姓名点击
    document.querySelectorAll('.featured-name').forEach(name => {
        name.addEventListener('click', function () {
            const origin = this.getAttribute('data-origin');
            cultureSelect.value = origin;

            if (origin === 'internet') {
                typeOptions.forEach(opt => opt.classList.remove('active'));
                document.querySelector('.type-option[data-type="internet"]').classList.add('active');
                genderGroup.style.display = 'none';
                generateInternetBtn.style.display = 'flex';
                generateBtn.style.display = 'none';
                generateInternetNames();
            } else {
                typeOptions.forEach(opt => opt.classList.remove('active'));
                document.querySelector('.type-option[data-type="real"]').classList.add('active');
                genderGroup.style.display = 'block';
                generateInternetBtn.style.display = 'none';
                generateBtn.style.display = 'flex';
                generateNames();
            }
        });
    });

    // 事件监听绑定
    generateBtn.addEventListener('click', generateNames);
    generateInternetBtn.addEventListener('click', generateInternetNames);
    resetBtn.addEventListener('click', resetForm);
    exportBtn.addEventListener('click', exportResults);

    // 显示含义选项变化时更新显示
    showMeaningCheckbox.addEventListener('change', () => {
        const nameCards = document.querySelectorAll('.name-card');
        if (nameCards.length > 0) {
            const names = Array.from(nameCards).map(card => ({
                name: card.querySelector('.name').textContent,
                meaning: card.querySelector('.meaning')?.textContent || '',
                origin: card.querySelector('.origin').textContent,
                gender: card.querySelector('.gender').classList.contains('male') ? 'male' :
                    card.querySelector('.gender').classList.contains('female') ? 'female' : 'unisex',
                type: card.classList.contains('internet') ? 'internet' : 'real'
            }));
            displayNames(names, showMeaningCheckbox.checked);
        }
    });

    // 初始化按钮显示状态
    generateInternetBtn.style.display = 'none';
    generateBtn.style.display = 'flex';
    genderGroup.style.display = 'block';

    // 初始化生成一些姓名
    generateNames();
});